package com.zhxin.nettylab.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.*;

import java.net.URI;

/**
 * @ClassName HttpClientHandler
 * @Description //HttpClientHandler
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2021/2/25 0025 下午 3:00
 **/
public class HttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        URI uri = new URI("http://localhost:8080");
        String msg ="hi,client test!";
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,uri.toASCIIString(),
                Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

        ctx.channel().writeAndFlush(request);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpResponse msg) throws Exception {

        FullHttpResponse response = msg;
        response.headers().get(HttpHeaderNames.CONTENT_TYPE);
        ByteBuf buf = response.content();

        System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
    }
}
